package com.example.demo.activemq.topic;

import com.alibaba.fastjson.JSON;
import com.example.demo.activemq.ActivemqContants;
import com.example.demo.activemq.ProducerConsumer;
import com.example.demo.activemq.model.ActiveModel;
import org.springframework.boot.json.JsonParseException;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.TextMessage;

public class TopicProducer extends ProducerConsumer {
    private int startNumber;
    private int endNumber;

    public TopicProducer(String name) throws JMSException {
        this.name = name;
        //通过工厂获取链接
        this.connection = this.getConnection();
        //开启链接
        this.connection.start();
        //获取session
        this.session = this.connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        //创建消息队列
        this.destination = this.session.createTopic(ActivemqContants.TOPIC_NAME);
        //创建生产者
        this.messageProducer = this.session.createProducer(this.destination);
    }

    public void sendMessage(String jsonData) throws JMSException {
        TextMessage textMessage = this.session.createTextMessage("I send the message: " + jsonData);
        System.out.println(textMessage.getText());
        this.messageProducer.send(textMessage);
    }

    public void sendMessage(ActiveModel activeModel) {
        try {
            sendMessage(JSON.toJSONString(activeModel));
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public void sendFinishMessage() throws JMSException {
        TextMessage textMessage = this.session.createTextMessage(ActivemqContants.FINISH_FLAG);
        System.out.println("Send finish flag: " + textMessage.getText());
        this.messageProducer.send(textMessage);
    }

    public void commit() throws JMSException {
        this.session.commit();
    }
}
